<script lang="ts" setup>
import { ref, nextTick, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import wpsNp, { IHightTextParams } from '@/utils/wps-ext'
import { v4 } from 'uuid'
import bus from 'vue3-eventbus'

interface Props {
  readonly?: boolean
}
const props = withDefaults(defineProps<Props>(), {
  readonly: true,
})
const isClose = ref(true)

const onFoo = () => {
  isClose.value = false
  bus.emit('wps-closed')
}
bus.on('removeTab', onFoo)

onBeforeUnmount(() => {
  bus.off('removeTab', onFoo)
})
// 加载状态
const loading = ref<boolean>(false)
// wpsId
const wpsId = ref<string>('')
// wps节点
let wpsExt: any = null
// 临时地址
const tempUrl = ref<string>('')
// 打开wps
const openWps = async (url: string) => {
  wpsId.value = 'wps' + v4()
  tempUrl.value = url
  await nextTick()
  loading.value = true
  wpsExt = wpsNp.createNew(document.getElementById(wpsId.value))
  // 展示wps
  await showWps()
}
// 展示wps
const showWps = async () => {
  try {
    await wpsExt.apis.openRemoteDoc({
      url: tempUrl.value,
      readOnly: props.readonly,
    })
    loading.value = false
  } catch (error) {
    ElMessage.error('文件打开失败, 请检查文件是否存在')
    loading.value = false
  }
}
/**
 * 高亮文字
 * @param params 高亮文字索引信息
 * @param colorIndex 颜色标识[0-7]
 */
const highText = async (params: IHightTextParams) => {
  const tempParams = Object.assign({ colorIndex: 7 }, params)
  try {
    await wpsExt.apis.highText(tempParams)
  } catch (error) {
    console.log(error)
  }
}

/**
 * 清理高亮文字
 * @param params 待清除高亮的文字信息
 */
const clearHighText = async (params?: IHightTextParams) => {
  await wpsExt.apis.clearHighText(params)
}

/**
 * 获取doc
 */
const saveToRemote = async (url: string) => {
  try {
    const params = {
      url: url,
    }
    loading.value = true
    const res = await wpsExt.apis.saveToRemote(params)
    loading.value = false
    const jsonData = JSON.parse(res)
    return jsonData?.data
  } catch (error) {
    ElMessage.error('文件打开失败, 请检查文件是否存在')
    loading.value = false
    return false
  }
}

defineExpose({ openWps, highText, clearHighText, saveToRemote })
</script>
<template>
  <!-- 加载wps -->
  <div v-if="isClose" v-loading="loading" class="wps-wrap" :id="wpsId"></div>
</template>
<style lang="scss" scoped>
.wps-wrap {
  width: 100%;
  height: 100%;
}
</style>
